package cn.dakaqi.pingan.util;

import cn.dakaqi.entities.PinganOpen;
import cn.dakaqi.pingan.entities.PingAnUser;
import cn.dakaqi.services.PinganNumberService;
import cn.dakaqi.services.PinganOpenService;
import cn.dakaqi.utils.Clock;
import cn.dakaqi.utils.DateUtil;
import cn.dakaqi.utils.http.HttpInvoker;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by chunyang on 2016/2/17.
 */
@Component(value = "openAccount")
@Transactional
public class OpenAccount
{
    private static Logger logger = LoggerFactory.getLogger(OpenAccount.class);
    @Autowired
    PinganNumberService pinganNumberService;
    @Autowired
    PinganOpenService pinganOpenRecordService;

    /**
     * 平安银行开户
     * @param type
     * @param volunteerCode
     * @param userName
     * @param IDCard
     * @param mobile
     * @param guardianName
     * @param guardianMobile
     * @param guardianIDCard
     * @return
     * @throws Exception
     */
    public PinganOpen regAccount(String customerCode,String memberCode,String type,String volunteerCode,String userName, String IDCard, String mobile,String guardianName,String guardianMobile,String guardianIDCard) throws Exception
    {

        logger.info("---------------------平安开户操作开始------------" + DateUtil.getToday());
        PinganOpen pinganOpen = null;
        String regAccountXML = "";

        //开户时的XML
        if(null == guardianName || StringUtils.isBlank(guardianName))
        {
            regAccountXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ROOT><userName>" + userName + "</userName><cardNumber>" + IDCard + "</cardNumber><mobile>" + mobile + "</mobile><channelType>0</channelType><umCode></umCode></ROOT>";
            //检查当前用户是否已开户
            pinganOpen = pinganOpenRecordService.findByMobileAndIdCard(mobile, IDCard);

        }
        else
        {
            regAccountXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ROOT><userName>" + guardianName + "</userName><cardNumber>" + guardianIDCard + "</cardNumber><mobile>" + guardianMobile + "</mobile><channelType>0</channelType><umCode></umCode></ROOT>";
            //检查当前用户是否已开户
            pinganOpen = pinganOpenRecordService.findByMobileAndIdCard(guardianMobile, guardianIDCard);
        }
        logger.info(regAccountXML);
        if(null != pinganOpen && StringUtils.isNotBlank(pinganOpen.getCardNum()))
        {
            logger.info("---------------------平安开户操作结束(本地库中已存在当前手机或身份证)------------" + DateUtil.getToday());
            return pinganOpen;
        }

        logger.info("开户时提交的XML:"+regAccountXML);
        //查询当前类型，当天目前最大编号+1 的流水号
        String sn = pinganNumberService.createNO(type);

        //A001字符开头，即如下定义的222报文头。
        String head = MessageHead.A001(regAccountXML, sn, PingAnUtil.tradeNO000001, PingAnUtil.shopNO);
        logger.info("开户时报文头长度:"+head.length() + ",A001定义的222报文头:" + head);
        //提交至平安银行
        String retValue = HttpInvoker.httpPostXML(PingAnUtil.B2BiUrl, head + regAccountXML);
        logger.info("开户时银行返回的信息:" + retValue);
        //截取银行返回的XML结果
        String xmlStr = retValue.substring(222, retValue.length());
        logger.info("开户时去除银行头后的信息:" + xmlStr);
        //将银行返回的XML组装银行开户数据对象
        PingAnUser pingAnUser = ParseXML.openResult(xmlStr);
        if(pingAnUser.getState().equals(PingAnUser.REG_STATE_SUCCESS))
        {
            if(pingAnUser.getIsNew().equals(PingAnUser.REG_ISNEW_YES))
            {
                //用户新开卡成功
                pinganOpen = savePinganBankRecord(customerCode,memberCode,type,sn,volunteerCode,userName,mobile,IDCard,guardianName,guardianMobile,guardianIDCard,pingAnUser.getCardNo());
            }
            else
            {
                //老用户，分为两种情况 1、是在本地开的户，2其他地方开的户
                pinganOpen = savePinganBankRecord(customerCode,memberCode,type,"", volunteerCode,userName, mobile, IDCard, guardianName,guardianMobile,guardianIDCard,pingAnUser.getCardNo());
            }
        }
        else
        {
            //开户异常
            throw new Exception(pingAnUser.getErrorMessage());
        }
        logger.info("---------------------平安开户操作结束------------" + DateUtil.getToday());
        return pinganOpen;
    }

    /**
     * 保存开户记录
     * @param sn
     * @param name
     * @param mobile
     * @param IDCard
     * @param cardNum
     */
    private PinganOpen savePinganBankRecord(String customerCode,String memberCode,String platfrom,String sn,String volunteerCode,String name,String mobile,String IDCard,String guardianName,String guardianMobile,String guardianIDCard,String cardNum)
    {
        PinganOpen pinganOpen = this.pinganOpenRecordService.findByVolunteerCode(volunteerCode);

        if(StringUtils.isEmpty(sn))
        {
            if(null == pinganOpen)
            {
                platfrom = "9";
                sn = pinganNumberService.createNO("");
                pinganOpen = new PinganOpen();
                pinganOpen.setSn(sn);
                pinganOpen.setName(name);
                pinganOpen.setMobile(mobile);
                pinganOpen.setIdCard(IDCard);
                pinganOpen.setGuardianName(guardianName);
                pinganOpen.setGuardianMobile(guardianMobile);
                pinganOpen.setGuardianIDCard(guardianIDCard);
                pinganOpen.setCardNum(cardNum);
                pinganOpen.setCreateTime(Clock.DEFAULT.getCurrentDate());
                pinganOpen.setPlatform(platfrom);
                pinganOpen.setStatus(PinganOpen.STATUS_NO);
                pinganOpen.setMemberCode(memberCode);
                pinganOpen.setCustomer(customerCode);
                pinganOpenRecordService.save(pinganOpen);
            }
            else
            {
                pinganOpen.setMemberCode(memberCode);
                pinganOpen.setSn(sn);
                pinganOpen.setName(name);
                pinganOpen.setMobile(mobile);
                pinganOpen.setIdCard(IDCard);
                pinganOpen.setGuardianName(guardianName);
                pinganOpen.setGuardianMobile(guardianMobile);
                pinganOpen.setGuardianIDCard(guardianIDCard);
                pinganOpen.setCardNum(cardNum);
                pinganOpen.setCreateTime(Clock.DEFAULT.getCurrentDate());
                pinganOpen.setPlatform(platfrom);
                pinganOpen.setStatus(PinganOpen.STATUS_NO);
                pinganOpen.setCustomer(customerCode);
                pinganOpenRecordService.save(pinganOpen);
            }
        }
        else
        {
            pinganOpen = new PinganOpen();
            pinganOpen.setMemberCode(memberCode);
            pinganOpen.setSn(sn);
            pinganOpen.setName(name);
            pinganOpen.setMobile(mobile);
            pinganOpen.setIdCard(IDCard);
            pinganOpen.setGuardianName(guardianName);
            pinganOpen.setGuardianMobile(guardianMobile);
            pinganOpen.setGuardianIDCard(guardianIDCard);
            pinganOpen.setCardNum(cardNum);
            pinganOpen.setCreateTime(Clock.DEFAULT.getCurrentDate());
            pinganOpen.setPlatform(platfrom);
            pinganOpen.setStatus(PinganOpen.STATUS_NO);
            pinganOpen.setCustomer(customerCode);
            pinganOpenRecordService.save(pinganOpen);
        }
        return pinganOpen;
    }

    /**
     * 检查当前手机、身份证是否已开过户
     * @param mobile
     * @param idCard
     * @return
     */
    private PinganOpen checkPinganBankRecord(String mobile, String idCard)
    {
        PinganOpen pinganOpen = pinganOpenRecordService.findByMobileAndIdCard(mobile,idCard);
        return pinganOpen;
    }
}
